package org.se.scut.pinterest.mina.codec.filte.coder.decoder;

import java.nio.charset.CharacterCodingException;
import java.nio.charset.Charset;
import java.nio.charset.CharsetDecoder;
import java.util.List;

import org.apache.mina.core.buffer.IoBuffer;
import org.apache.mina.core.session.AttributeKey;
import org.apache.mina.core.session.IoSession;
import org.apache.mina.filter.codec.demux.MessageDecoder;
import org.apache.mina.filter.codec.demux.MessageDecoderResult;
import org.se.scut.pinterest.mina.codec.coder.cxt.BaseContext;

public abstract class BaseMessageDecoder implements MessageDecoder {

	protected static final CharsetDecoder DECODER = Charset.forName("UTF-8").newDecoder();
	protected String msgSymbol;
	protected  AttributeKey CONTEXT_KEY;
	
	protected BaseMessageDecoder(AttributeKey key, String msgSymbol){
		this.CONTEXT_KEY = key;
		this.msgSymbol = msgSymbol;
	}
	
	@Override
	public MessageDecoderResult decodable(IoSession session, IoBuffer in) {
		if (in.remaining() < 3) {
			return MessageDecoderResult.NEED_DATA;
		}
		else {
			if (msgSymbol.contains(getSymbol(in))) {
				return MessageDecoderResult.OK;
			}else {
				return MessageDecoderResult.NOT_OK;
			}
		}
	}
	
	public abstract BaseContext getContext(IoSession session);

	public  String getSymbol(IoBuffer in)
	{
		IoBuffer buffer = IoBuffer.allocate(4).setAutoExpand(true);
		int i = 0;
		while (in.hasRemaining()) {
			byte b = in.get();
			i++;
			buffer.put(b);
			if (b == 10) {
				break;
			}
		}
		String symbol = "";
		try {
			buffer.flip();
			symbol = buffer.getString(i, DECODER);
			symbol = symbol.substring(0, symbol.length() - 1);
		} catch (CharacterCodingException e1) {
			e1.printStackTrace();
		}
		return symbol;
	}
}
